﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using InfoJetSoft.Service;
using Microsoft.SharePoint;
using System.Xml;
using System.Xml.XPath;
using System.Text;
using Microsoft.SharePoint.Workflow;
using ServBus.ListForm2013.Utility;
using ServBus.ListForm2013.Extension;
using Microsoft.SharePoint.WebControls;
using ServBus.ListForm2013.License;
using Microsoft.SharePoint.WorkflowServices;
using System.Web;

namespace ServBus.ListForm2013.Layouts.ListForm2013
{
    public partial class ListFormWFInner : LayoutsPageBase
    {
        #region Parameters

        private string _siteName;//"http://win-3ststb2hjp7";
        private Guid _webName;//"Test";
        private string _listId = "";//"test";
        private string _ctypeId = "";
        private string _itemId = "";//string.Empty;
        private string _xsnLocation = "";
        private string _errorMsg = "";
        private string _ctypeName = "";
        private string _MlistId = "";
        private string _MItemId = "";
        private string _HlistId = "";
        private string _WInstanceId = "";

        private readonly Dictionary<string, Dictionary<int, string>> SItemsId = new Dictionary<string, Dictionary<int, string>>();

        private XmlNamespaceManager _xNameSpace;

        #endregion

        private void errorLog(Exception ex, bool internalError)
        {

            if (internalError)
            {
                errorPanel.Visible = true;
            }
            ////else
            {
#if DEBUG
                errorPanel.Visible = false;
                LTException.Text = ex.Message;
                LTException.Visible = true;
#else
                LTException.Text = ex.Message;
                LTException.Visible = false;
#endif
            }
            ErrorLog.Write("ListFormWFInner" + "\r\n" + Request.Url + "\r\n" + ex.Message + "\r\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
}
        private void Notice_RefreshXSN()
        {
            refreshPanel.Visible = true;
			}

        #region Page Method

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    Activations activations = new Activations(SPContext.Current.Site.WebApplication);
                    if (!activations.IsActivationValid(SPContext.Current.Web, out _errorMsg))
                    {
                        errorLog(new Exception(_errorMsg), false);
                    }
                    else
                    {
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableRichText(true);
                        InfoJetSoft.Service.Util.ConfigUtil.EditRichTextOnFocus = true;
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableFormFieldsCache(true);
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnablePlaceholderUI(true);
                        InfoJetSoft.Service.Util.ConfigUtil.SetEnableMasterDetailsPopup(true);

                        _listId = Page.Request["listId"];
                        _ctypeId = Page.Request["ctype"];
                        _siteName = SPContext.Current.Site.Url;

                        _webName = SPContext.Current.Web.ID;

                        _xNameSpace = new XmlNamespaceManager(new NameTable());
                        _xNameSpace.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
                        _xNameSpace.AddNamespace("tns", "http://tempuri.org/");
                        _xNameSpace.AddNamespace("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
                        if (Page.IsPostBack) return;
                       
                                _itemId = Page.Request["itemId"];
                                GenerateEditForm();
                    }
                }
            }
            catch (Exception ex)
            {
                errorLog(ex, true);
            }
        }

        protected void DeleteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(_siteName))
                    {
                        using (SPWeb web = site.OpenWeb(_webName))
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList list = web.Lists[new Guid(_listId)];
                            int itemId = Convert.ToInt32(_itemId);
                            SPListItem item = list.GetItemById(itemId);
                            item.Recycle();
                        }
                    }
                });
                Response.Write("<script type='text/javascript'>parent.closeFormPart();</script>");

            }
            catch (Exception ex)
            {
                errorLog(ex, true);
            }
        }
        #endregion

        #region Private Method        

        private void GenerateEditForm()
        {
            SItemsId.Clear();
            string xmlTemplate = GetXMLTemplate().Xml;
            if (xmlTemplate != string.Empty)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xmlTemplate);

                //SPSecurity.RunWithElevatedPrivileges(delegate
                //{
                    using (SPSite site = new SPSite(_siteName))
                    {
                        using (SPWeb web = site.OpenWeb(_webName))
                        {
                            SPList list = web.Lists[new Guid(_listId)];
                            SPContentTypeId contentTypeId = new SPContentTypeId(_ctypeId.ToLower());
                            _ctypeName = list.ContentTypes[contentTypeId].Name;
                            int itemId = Convert.ToInt32(_itemId);
                            SPListItem item = list.GetItemById(itemId);

                            try
                            {
                            XmlNode tNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:Task", _xNameSpace);
                            foreach (XmlNode xNode in tNode.ChildNodes)
                            {
                                SetListFieldsValue(xNode, list, item);
                            }
							}
                            catch (Exception)
                            {
                                Notice_RefreshXSN();
                            }
                            string wfVersion = "";
                            if (item.ContentTypeId.IsChildOf(Constants.WFTask_ContentType_Id))
                            {
                                string relatedItemsValue = Convert.ToString(item[SPBuiltInFieldId.RelatedItems]);
                                if (relatedItemsValue.Contains("ItemId"))
                                {
                                    string listItemId = relatedItemsValue.Substring(relatedItemsValue.IndexOf("ItemId") + 8);
                                    listItemId = listItemId.Substring(0, listItemId.IndexOf(","));
                                    _MItemId = listItemId;
                                }
                                if (relatedItemsValue.Contains("ListId"))
                                {
                                    string listId = relatedItemsValue.Substring(relatedItemsValue.IndexOf("ListId") + 9);
                                    listId = listId.Substring(0, listId.IndexOf("\""));
                                    _MlistId = listId;
                                }
                                _WInstanceId = Convert.ToString(item["WF4InstanceId"]);
                                wfVersion = "v4";
                                WorkflowServicesManager manager = new WorkflowServicesManager(web);
                                if (manager.IsConnected)
                                {
                                    WorkflowInstanceService workflowInstanceService = manager.GetWorkflowInstanceService();
                                    if (workflowInstanceService != null)
                                    {
                                        WorkflowInstance workflowInstance = workflowInstanceService.GetInstance(new Guid(_WInstanceId));
                                        WorkflowSubscription ws = manager.GetWorkflowSubscriptionService().GetSubscription(workflowInstance.WorkflowSubscriptionId);
                                        _HlistId = ws.PropertyDefinitions.ContainsKey("HistoryListId") ? ws.PropertyDefinitions["HistoryListId"] : string.Empty;

                                    }
                                }
                            }
                            else
                            {
                                _MlistId = Convert.ToString(item[SPBuiltInFieldId.WorkflowListId]).TrimStart(new char[] { '{' }).TrimEnd(new char[] { '}' });
                                _MItemId = Convert.ToString(item[SPBuiltInFieldId.WorkflowItemId]);
                                _WInstanceId = Convert.ToString(item[SPBuiltInFieldId.WorkflowInstanceID]);
                                wfVersion = "v3";
                                SPWorkflow spWF = new SPWorkflow(item, new Guid(_WInstanceId));
                                _HlistId = Convert.ToString(spWF.HistoryListId);
                            }
                            
                            SPList mList = web.Lists[new Guid(_MlistId)];
                            int mItemId = Convert.ToInt32(_MItemId);
                            SPListItem mitem = mList.GetItemById(mItemId);
                            _ctypeName = "";
                            XmlNode mNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:RelatedContent", _xNameSpace);
                            foreach (XmlNode xNode in mNode.ChildNodes)
                            {
                                SetListFieldsReadOnlyValue(xNode, mList, mitem);
                            }
                            
                            SPList hList = web.Lists[new Guid(_HlistId)];
                            _ctypeName = hList.ContentTypes[0].Name;
                            XmlNode wNode = xDoc.SelectSingleNode("/dfs:myFields/dfs:dataFields/tns:WorkflowHistory", _xNameSpace);
                            SetLkpFormValue(wNode, hList);

                            InfoJetContext ijCtx = new InfoJetContext
                            {
                                InlineFileStorage = new InlineFileStorage(),
                                ExportFileStorage = new ExportFileStorage()
                            };

                            RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                            ijCtx.RelativeUrlResolver = resolver;
                            //Start:14-2-26 Attachments Feature add
                            if(mList.Fields.ContainsFieldWithStaticName("Attachments"))
                            {
                            string attachmentsPath = "/dfs:myFields/dfs:dataFields/tns:RelatedContent/tns:" + mList.Title + "__Attachments";
                            string[] attachmentsUrlStrings = new string[mitem.Attachments.Count];
                            for (int i = 0; i < mitem.Attachments.Count; i++)
                            {
                                attachmentsUrlStrings[i] = mitem.Attachments.UrlPrefix + mitem.Attachments[i];
                            }
                            ijCtx.SetListAttachments(attachmentsPath, attachmentsUrlStrings);
                            ijCtx.IsListAttachmentsReadonly = true;
                            }
                            //End:14-2-26 Attachments Feature add
                            //if (!IsCurrentUserBeAssignedTo(web, item)) ijCtx.IsReadonly = true;
                            //if (hasCompleted(item)) ijCtx.IsReadonly = true;
                            InfoJetForm editForm = InfoJetService.BuildFormByXML(Context, ijCtx, _xsnLocation, xDoc.OuterXml);
                            xDocViewInner.Text = editForm.Xhtml;
                        }
                    }
                //});
            }
        }

        private bool RegisterXSNTemplate()
        {
            Guid xsnId;

            byte[] xsnContent;

            bool succeed = false;
            InfoJetService.License(Constants.InfoJetLicense);



            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(_siteName))
                {
                    using (SPWeb web = site.OpenWeb(_webName))
                    {
                        SPList list = web.Lists[new Guid(_listId)];
                        SPContentTypeId contentTypeId = new SPContentTypeId(_ctypeId.ToLower());
                        SPContentType cType = list.ContentTypes[contentTypeId];
                        int itemId = Convert.ToInt32(_itemId);
                        SPListItem item = list.GetItemById(itemId);
                        string wfAssId = "";
                        if (item.ContentTypeId.IsChildOf(Constants.WFTask_ContentType_Id))
                        {
                            _WInstanceId = Convert.ToString(item["WF4InstanceId"]);
                            WorkflowServicesManager manager = new WorkflowServicesManager(web);
                            if (manager.IsConnected)
                            {
                                WorkflowInstanceService workflowInstanceService = manager.GetWorkflowInstanceService();
                                if (workflowInstanceService != null)
                                {
                                    WorkflowInstance workflowInstance = workflowInstanceService.GetInstance(new Guid(_WInstanceId));
                                    wfAssId = Convert.ToString(workflowInstance.WorkflowSubscriptionId);
                                }
                            }
                        }
                        else
                        {
                            _WInstanceId = Convert.ToString(item[SPBuiltInFieldId.WorkflowInstanceID]);
                             SPWorkflow spWF = new SPWorkflow(item, new Guid(_WInstanceId));
                             wfAssId = Convert.ToString(spWF.AssociationId);

                        }
                        _xsnLocation = web.Url + "/" + cType.ResourceFolder.Url + "/template-" + wfAssId + ".xsn";
                        
                        SPFile file = web.GetFile(_xsnLocation);
                        if (file.Exists)
                        {
                            xsnContent = file.OpenBinary();
                            xsnId = file.UniqueId;


                            if (xsnContent == null)
                            {
                                succeed = false;
                            }
                            else
                            {
                                string md5 = CryptoUtility.ComputeMD5(xsnContent);
                                if (InfoJetService.GetMD5(_xsnLocation) == md5)
                                {
                                    succeed = true;
                                }
                                else
                                {
                                    InfoJetContext ijCtx = new InfoJetContext();
                                    ijCtx.Variables.Add("InfoBus_XsnId", xsnId.ToString());
                                    ijCtx.ResourceFileStorage = new ResourceFileStorage(web);
                                    ijCtx.InlineFileStorage = new InlineFileStorage();
                                    succeed = InfoJetService.RegisterWithMD5(Context, ijCtx, _xsnLocation, xsnContent, "/_layouts/15/ListForm2013/", md5);
                                }
                            }


                        }
                        else
                        {
                            succeed = false;

                        }
                    }
                }
            });
            return succeed;
        }

        private InfoJetForm GetXMLTemplate()
        {
            if (RegisterXSNTemplate())
            {

                InfoJetContext ijCtx = new InfoJetContext
                {
                    InlineFileStorage = new InlineFileStorage(),
                    ExportFileStorage = new ExportFileStorage()
                };
                RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                ijCtx.RelativeUrlResolver = resolver;
                //if (!string.IsNullOrEmpty(viewId))
                //{
                //    ijCtx.ViewName = viewId;
                //}
                InfoJetForm newForm = InfoJetService.BuildFormByTemplate(Context, _xsnLocation, ijCtx);
                return newForm;
            
            }
            
            return null;
        }

        private void SetListFieldsValue(XmlNode xNode, SPList plist, SPListItem p_Item)
        {
            if (xNode.HasChildNodes)
            {
                foreach (XmlNode cXNode in xNode.ChildNodes)
                {
                    SetListFieldsValue(cXNode, plist, p_Item);
                }
            }
            SetValue(xNode.CreateNavigator(), plist, p_Item);
        }

        private void SetListFieldsReadOnlyValue(XmlNode xNode, SPList plist, SPListItem p_Item)
        {
            if (xNode.HasChildNodes)
            {
                foreach (XmlNode cXNode in xNode.ChildNodes)
                {
                    SetListFieldsValue(cXNode, plist, p_Item);
                }
            }
            SetReadOnlyValue(xNode.CreateNavigator(), plist, p_Item);
        }

        private void SetLkpFormValue(XmlNode xNode, SPList hList)
        {
            XmlNode node = xNode;

            if (node.Attributes != null)
            {
                List<XmlNode> addSContentTypeNode = new List<XmlNode>();
                XmlNode sContentTypeNode = node;
                if (sContentTypeNode.Attributes != null)
                {
                    SPListItemCollection resultItems = GetLkpSubItems(hList, _WInstanceId);
                    foreach (SPListItem sItem in resultItems)
                    {
                        XmlNode sItemNode = sContentTypeNode.Clone();
                        sItemNode.CreateNavigator();
                        //sItemNav.CreateAttribute("", "ItemID", "", sItem.ID.ToString());
                        if (sItemNode.Attributes != null)
                            sItemNode.Attributes["Item_ID"].Value = sItem.ID.ToString(CultureInfo.InvariantCulture);

                        foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                        {
                            SetReadOnlyValue(sFieldNode.CreateNavigator(), hList, sItem);
                        }

                        //XPathNavigator listNav = rootNav.SelectSingleNode(string.Format("/dfs:myFields/dfs:dataFields/tns:mainForm/tns:SubForms/tns:{0}", listNode.LocalName), xNameSpace);
                        //listNav.AppendChild(sItemNav);
                        addSContentTypeNode.Add(sItemNode);
                    }
                }

                node.RemoveAll();
                XPathNavigator listNav = node.CreateNavigator();
                listNav.CreateAttribute("", "List_ID", "", hList.ID.ToString());
                foreach (XmlNode addNode in addSContentTypeNode)
                {
                    node.ParentNode.InsertAfter(addNode, node);
                }
                node.ParentNode.RemoveChild(node);
            }
        }

        private SPListItemCollection GetLkpSubItems(SPList hList, string instanceId)
        {
                SPQuery query = new SPQuery
                {
                    Query = string.Format("<Where><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq></Where>",
                        "WorkflowInstance", instanceId)
                };

            return hList.GetItems(query);
        }

        private void SetValue(XPathNavigator p_XPathNav, SPList plist, SPListItem p_Item)
        {
            if (p_XPathNav != null)
            {
                string uniquePrefix = string.Format("{0}_{1}_", plist.Title, _ctypeName).Replace(" ", "_");
                uniquePrefix = ServBus.ListForm2013.Common.WFXSNOperator.FieldHelper.GetUniquefieldName(uniquePrefix);
                string localName = p_XPathNav.LocalName.Replace(uniquePrefix, "");
                

                //begin looping through the nodes
                if (!string.IsNullOrEmpty(localName))
                {
                    #region Set Value

                    string mFieldInternalName = localName;
                    if (plist.Fields.ContainsField(mFieldInternalName))
                    {
                        SPField mField = plist.Fields.GetField(mFieldInternalName);

                        string mFieldValue = GetFormValueFromField(mField, p_Item);

                        if (string.IsNullOrEmpty(mFieldValue))
                        {
                            return;
                        }

                        //根据不同的Field类型，表单对应不同的数据类型，这里需要判断
                        switch (mField.Type)
                        {
                            case SPFieldType.Number:
                                DeleteNil(p_XPathNav);
                                p_XPathNav.SetValue(mFieldValue);
                                break;

                            case SPFieldType.DateTime:
                                DeleteNil(p_XPathNav);
                                SPFieldDateTime dateTimeField = (SPFieldDateTime)mField;
                                //DateOnly
                                if (dateTimeField.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
                                {
                                    DateTime dt = DateTime.Parse(mFieldValue);
                                    p_XPathNav.SetValue(dt.Date.ToString("yyyy-MM-dd"));
                                }
                                else
                                {
                                    DateTime dt = DateTime.Parse(mFieldValue);
                                    p_XPathNav.SetValue(dt.Date.ToString("s"));
                                }
                                break;

                            case SPFieldType.User:
                                //if (p_xPathNav.InnerXml == "")
                                //{
                                //    return;
                                //}
                                InsertToUserType(p_Item, mField.Id, p_XPathNav);
                                break;

                            case SPFieldType.MultiChoice:
                                InsertIntoCheckBoxType(mFieldValue, p_XPathNav, p_XPathNav.LocalName);
                                break;

                            case SPFieldType.Note:
                                SPFieldMultiLineText noteField = (SPFieldMultiLineText)mField;
                                if (noteField.RichText)
                                {
                                    p_XPathNav.InnerXml = mFieldValue;
                                }
                                else
                                {
                                    p_XPathNav.InnerXml = noteField.GetFieldValueAsText(p_Item[mFieldInternalName]);
                                }
                                break;
                            case SPFieldType.Lookup:
                                p_XPathNav.SetValue(mFieldValue);
                                break;

                            default:
                                p_XPathNav.SetValue(mFieldValue);
                                break;
                        }
                    }
                    #endregion
                }
            }
        }

        private void SetReadOnlyValue(XPathNavigator p_XPathNav, SPList plist, SPListItem p_Item)
        {
            if (p_XPathNav != null)
            {
                string uniquePrefix = string.Format("{0}_{1}_", plist.Title, _ctypeName).Replace(" ", "_");
                uniquePrefix = ServBus.ListForm2013.Common.WFXSNOperator.FieldHelper.GetUniquefieldName(uniquePrefix);
                string localName = p_XPathNav.LocalName.Replace(uniquePrefix, "");

                //begin looping through the nodes
                if (!string.IsNullOrEmpty(localName))
                {
                    #region Set Value

                    string mFieldInternalName = localName;
                    if (plist.Fields.ContainsField(mFieldInternalName))
                    {
                        SPField mField = plist.Fields.GetField(mFieldInternalName);

                        string mFieldValue = GetFormValueFromField(mField, p_Item);

                        if (string.IsNullOrEmpty(mFieldValue))
                        {
                            return;
                        }
                        else
                        {
                            if (mFieldInternalName.Equals("LinkFilename"))
                            {
                                SPFile file = p_Item.File;
                                string filePath = Microsoft.SharePoint.Utilities.SPUtility.MapToServerFileRedirect(p_Item.Web, (string)p_Item[SPBuiltInFieldId.EncodedAbsUrl], file.ProgID);
                                if (!string.IsNullOrEmpty(filePath))
                                {
                                    if (filePath.EndsWith(".xml")) filePath = filePath + "&DefaultItemOpen=1";
                                    p_XPathNav.SetValue(filePath);
                                }
                                else p_XPathNav.SetValue((string)p_Item[SPBuiltInFieldId.EncodedAbsUrl]);
                            }
                            else if (mFieldInternalName.Equals("LinkTitle"))
                            {
                                string displayFormUrl = plist.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + p_Item.ID;
                                p_XPathNav.SetValue(plist.ParentWeb.Url + "/" + displayFormUrl);
                            }
                            else if (mField.Type.Equals(SPFieldType.WorkflowEventType))
                            {
                                int eventValue = Convert.ToInt32(mField.GetFieldValueAsText(p_Item[mField.Id]));
                                p_XPathNav.SetValue(Enum.GetName(typeof(SPWorkflowHistoryEventType), eventValue));
                            }
                            else
                            {
                                p_XPathNav.SetValue(mField.GetFieldValueAsText(p_Item[mField.Id]));
                            }
                        }
                    }
                    #endregion
                }
            }
        }
        /// <summary>
        /// 从列表的Field中获取值填充到InfoPath节点中
        /// </summary>
        /// <param name="p_Field"></param>
        /// <param name="p_Item"></param>
        /// <returns></returns>
        private string GetFormValueFromField(SPField p_Field, SPListItem p_Item)
        {

            string mStrValue = string.Empty;
            try
            {

                if (p_Item[p_Field.Id] == null)
                {
                    return mStrValue;
                }
                else if (string.IsNullOrEmpty(Convert.ToString(p_Item[p_Field.Id])))
                {
                    return mStrValue;
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                return mStrValue;
            }


            switch (p_Field.Type)
            {
                case SPFieldType.Lookup:
                    string mLookupValue = p_Item[p_Field.Id].ToString();

                    int tIndex = mLookupValue.IndexOf("#", StringComparison.Ordinal);
                    mStrValue = mLookupValue.Substring(0, tIndex - 1);
                    //m_str_value = m_lookup_value;                   //读取数据时出错。TO DO...目前先临时改回来
                    break;

                case SPFieldType.DateTime:
                    DateTime mTime = (DateTime)p_Item[p_Field.Id];
                    mStrValue = Convert.ToString(mTime);
                    break;

                case SPFieldType.Note:
                    //Obsolete

                    mStrValue = Convert.ToString(p_Item[p_Field.Id]);
                    mStrValue = GetMulitTextString(mStrValue);
                    break;

                case SPFieldType.URL:
                    SPFieldUrlValue urlValue = new SPFieldUrlValue(Convert.ToString(p_Item[p_Field.Id]));
                    mStrValue = urlValue.Url;
                    break;

                case SPFieldType.Boolean:
                    bool booleanField = Convert.ToBoolean(p_Item[p_Field.Id]);
                    mStrValue = booleanField ? "true" : "false";
                    break;

                default:
                    mStrValue = Convert.ToString(p_Item[p_Field.Id]);
                    break;
            }
            return mStrValue;
        }

        /// <summary>
        /// 架构验证发现无数据类型错误的解决方案，目前只用于数字类型
        /// </summary>
        /// <param name="node">当前节点</param>
        private void DeleteNil(XPathNavigator node)
        {
            if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
            {
                node.DeleteSelf();
            }
        }

        /// <summary>
        /// 插入用户信息到pc:Person类型的节点中
        /// </summary>
        /// <param name="fieldTitle"></param>
        /// <param name="xPathNav"></param>
        /// <param name="item"></param>
        private void InsertToUserType(SPListItem item, Guid fieldId, XPathNavigator xPathNav)
        {
            string pcValue;
            if (xPathNav.HasChildren)
            {
                xPathNav.SetValue("");
            }
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(_siteName))
                {
                    using (site.OpenWeb(_webName))
                    {
                        try
                        {
                            SPFieldUser userField = (SPFieldUser)item.Fields[fieldId];
                            SPFieldUserValue userValue = (SPFieldUserValue)userField.GetFieldValue(Convert.ToString(item[fieldId]));
                            SPUser user = userValue.User;
                            pcValue = "<pc:Person><pc:DisplayName>" + user.Name + "</pc:DisplayName><pc:AccountId>" + user.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                            xPathNav.AppendChild(pcValue);

                        }
                        catch
                        {
                            SPFieldUserValueCollection userValues = item[fieldId] as SPFieldUserValueCollection;

                            if (userValues != null)
                                foreach (SPFieldUserValue userValue in userValues)
                                {
                                    SPUser user = userValue.User;
                                    if (user != null)
                                    {
                                        pcValue = "<pc:Person><pc:DisplayName>" + user.Name + "</pc:DisplayName><pc:AccountId>" + user.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                                        xPathNav.AppendChild(pcValue);
                                    }
                                    else
                                    {
                                        SPGroup group = Web.Groups.GetByID(userValue.LookupId);
                                        pcValue = "<pc:Person><pc:DisplayName>" + group.Name + "</pc:DisplayName><pc:AccountId>" + group.LoginName + "</pc:AccountId><pc:AccountType>Group</pc:AccountType></pc:Person>";
                                        xPathNav.AppendChild(pcValue);
                                    }
                                }
                        }
                    }
                }
            });

        }

        private void InsertIntoCheckBoxType(string fieldValue, XPathNavigator xPathNav, string fieldName)
        {
            fieldName = fieldName + "_1";
            SPFieldMultiChoiceValue choiceValue = new SPFieldMultiChoiceValue(fieldValue);

            string myNamespace = "xmlns:my=\"http://tempuri.org/\"";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < choiceValue.Count; i++)
            {
                sb.AppendFormat("<tns:{0} {2}>{1}</tns:{0}>", fieldName, choiceValue[i], myNamespace);
            }
            xPathNav.AppendChild(sb.ToString());
        }

        private string GetMulitTextString(string p_Field_String)
        {
            string mComment;
            try
            {

                XmlDocument mDoc = new XmlDocument();
                mDoc.LoadXml(p_Field_String);

                mComment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + mDoc.InnerXml + "</div>";

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mComment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + p_Field_String + "</div>";
            }

            return mComment;
        }

        #endregion
    }
}
